package com.eco.fanliapp.eureke.event;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author zhuchao
 * @create 2019-09-25 13:27
 */
//@Component
public class EurekaStateListener {
	private final static Logger log = LoggerFactory.getLogger(EurekaStateListener.class);
	/**
	 * 手机号
	 * 安安：13569206925
	 * LYL：15038199903
	 * 可可：18939253811
	 * 七七：13938631583
	 * 王跃：18839357210
	 * 冲哥：18610457573
	 * 祝超：15117916955
	 */
	static final String accessKeyId = "LTAI4Fggg71m9wvDhN3AiinZ";
	static final String accessKeySecret = "5qXJd58cW96NwebiXxfEZmSsDwu4kx";
	static final String phoneNumber = "13569206925,15038199903,18939253811,13938631583,18839357210,18610457573,15117916955";
	static final String SignName = "省鸭";
	static final String TemplateCode = "SMS_185855007";

	@Autowired
	private JavaMailSender jms;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 上线服务
	 * @param event
	 */
	@EventListener
	public void listen(EurekaInstanceRegisteredEvent event) {
		InstanceInfo instanceInfo = event.getInstanceInfo();
		log.info("获取服务{}注册名称",event.getInstanceInfo());
		log.info("服务{}进行注册", instanceInfo.getAppName() + instanceInfo.getHostName() +"  "+ instanceInfo.getIPAddr() +"  "+ instanceInfo.getPort());
		//（正式环境打开）
//		ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
//		opsForValue.set(instanceInfo.getInstanceId(),instanceInfo.getInstanceId());
		log.info(">>>>>>> 服务名:{},端口号:{},已缓存至redis", instanceInfo.getAppName() , instanceInfo.getPort());

	}

	/**
	 * 下线服务
	 * @param event
	 */
	@EventListener
	public void listen(EurekaInstanceCanceledEvent event) {
		log.info("服务{}已下线", event.getAppName());
		String[] split = event.getServerId().split(":");
		String param  = "ip:" + split[0] + "名称:" + split[1] + "端口:" + split[2];
		String mes = SendSms(split[0],split[1],split[2]);
		log.info("服务异常短信发送结果:{}",mes);
		log.info("server地址信息{}", event.getServerId());
		//（正式环境打开）
		//handlerMessage(event);
	}

	@EventListener
	public void listen(EurekaInstanceRenewedEvent event) {
		log.info("服务{}进行续约", event.getServerId() +"  "+ event.getAppName());
	}

	@EventListener
	public void listen(EurekaRegistryAvailableEvent event) {
		log.info("注册中心启动,{}", System.currentTimeMillis());
	}

	@EventListener
	public void listen(EurekaServerStartedEvent event) {
		log.info("注册中心服务端启动,{}", System.currentTimeMillis());
	}

	/**
	 * 处理服务下线消息通知
	 * @param event
	 */
	private void handlerMessage(EurekaInstanceCanceledEvent event){
		try {
			//如果完全匹配不到这个key，直接结束，（防止重复发送消息）
			Set<String> keys1 = stringRedisTemplate.keys(event.getServerId());
			if(keys1.size() == 0){
				return;
			}
			log.info("=========开始处理发送消息的逻辑==========");
			//redis移除服务
			stringRedisTemplate.delete(event.getServerId());
			log.info(">>>>>>> 失效服务:{},已被剔除!", event.getServerId());

			//发送消息
			//sendEmail(event.getAppName(),"服务下线通知：===》" + event.getServerId());
			//sendMesage(event.getAppName() + "服务已下线");


		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 发送短信
	 * @param content
	 */
	/**
	 * SendSms接口是短信发送接口，支持在一次请求中向多个不同的手机号码发送同样内容的短信。
	 * @return
	 */
	public static String SendSms(String ip, String serverName, String port) {
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");

		//此处放接收验证码的手机号
		request.putQueryParameter("PhoneNumbers", phoneNumber);
		//此处放签名名称（必须审核通过）
		request.putQueryParameter("SignName", SignName);
		//此处放短信模板（必须审核通过）
		request.putQueryParameter("TemplateCode", TemplateCode);
		//此处放验证码的内容（JSON格式\"表示转义。JSON格式：{"code":"666666"}）
		String TemplateParam = "{\"ip\":\"" + ip + "\",\"serverName\":\"" + serverName + "\",\"port\":\"" + port + "\"}";

		request.putQueryParameter("TemplateParam", TemplateParam);

		try {
			CommonResponse response = client.getCommonResponse(request);
			return response.getData();
		} catch (com.aliyuncs.exceptions.ServerException e) {
			e.printStackTrace();
		} catch (com.aliyuncs.exceptions.ClientException e) {
			e.printStackTrace();
		}
		return "服务异常阿里云短信发送失败";
	}

	/**
	 * 发送邮件
	 * @param msg
	 */
	private  void sendEmail(String title,String msg){
		log.info("开始发送邮件");
		//用于封装邮件信息的实例
		SimpleMailMessage smm=new SimpleMailMessage();
		//由谁来发送邮件
		smm.setFrom("1247964593@qq.com");//该邮件的密码在配置文件中
		//邮件主题
		smm.setSubject(title);
		//邮件内容
		smm.setText(msg);
		//接受邮件
		//smm.setTo(new String[]{"1731392667@qq.com","591354909@qq.com","1186113222@qq.com"});
		smm.setTo(new String[]{"1731392667@qq.com"});
		try {
			jms.send(smm);
		} catch (Exception e) {
			log.info(msg+"错误",e);
		}
	}
}

